package com.campusevaluation.utils;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTValidator;
import cn.hutool.jwt.signers.JWTSigner;
import cn.hutool.jwt.signers.JWTSignerUtil;
import com.campusevaluation.common.exception.UnauthorizedException;
import org.springframework.stereotype.Component;
import java.security.KeyPair;
import java.time.Duration;
import java.util.Date;
@Component
public class JwtUtil {

    private final JWTSigner jwtSigner;

    public JwtUtil(KeyPair keyPair) {
        this.jwtSigner = JWTSignerUtil.createSigner("rs256", keyPair);
    }

    public String createToken(Long userId, Duration ttl) {
        return JWT.create()
                .setPayload("user", userId)
                .setExpiresAt(new Date(System.currentTimeMillis() + ttl.toMillis()))
                .setSigner(jwtSigner)
                .sign();
    }

    public Long parseToken(String token) {
        // 校验token是否为空
        if (token == null) {
            throw new UnauthorizedException("未登录");
        }
        // 校验并解析jwt
        JWT jwt;
        try {
            jwt = JWT.of(token).setSigner(jwtSigner);
        } catch (Exception e) {
            throw new UnauthorizedException("无效的token", e);
        }
        // 检验jwt是否有效
        if (!jwt.verify()) {
            throw new UnauthorizedException("无效的token");
        }
        // 校验jwt是否过期
        try {
            JWTValidator.of(jwt).validateDate();
        } catch (Exception e) {
            throw new UnauthorizedException("token已过期");
        }
        // 数据校验格式
        Object payload = jwt.getPayload("user");
        if (payload == null) {
            throw new UnauthorizedException("无效的token");
        }
        try {
            return Long.valueOf(payload.toString());
        } catch (Exception e) {
            throw new UnauthorizedException("无效的token");
        }
    }
}
